// 导入 express 并创建服务器
const express = require("express");
const app = express();

// 导入并注册 cors 跨域中间件
const cors = require("cors");
app.use(cors());

const config = require("./config");

// 在路由的 res 对象上添加 cc() 方法
app.use((req, res, next) => {
  res.cc = (err, status = 0) => {
    err = err instanceof Object ? err.message : err;
    res.send({
      status,
      message: err,
    });
  }
  next();
})

// 导入并注册token解析中间件
const expressJwt = require("express-jwt");
app.use(expressJwt({ secret: config.jwtSecretKey, algorithms: ['HS256'] }).unless({ path: [/^\/api\//, /^\/assets\//, /^\/goods\//, /^\/getType\//, /^\/banner\//, /^\/general/] }));

// 注册接收json格式参数和urlencoded格式参数的中间件
app.use(express.json());
app.use(express.urlencoded({ extended: false }));

//静态资源托管
app.use("/assets", express.static("./assets"));
app.use("/general", express.static("./public/general"));


// 导入并注册 user 路由模块 
const userRouter = require("./router/user.js");
app.use("/api", userRouter);

// 导入并注册 userinfo 路由模块
const userinfoRouter = require("./router/userinfo");
app.use("/userinfo", userinfoRouter);

// 导入并注册 goods 模块
const goodsRouter = require("./router/goods");
app.use("/goods", goodsRouter);

// 导入并注册 setGoods 模块
const setGoodsRouter = require("./router/setGoods");
app.use("/setGoods", setGoodsRouter);

// 导入并注册 getType 模块
const getTypeRouter = require("./router/getType");
app.use("/getType", getTypeRouter);

// 导入并注册 shoppingCart 路由模块
const shoppingCartRouter = require("./router/shoppingCart");
app.use("/shoppingCart", shoppingCartRouter);

// 导入并注册 order 路由模块
const orderRouter = require("./router/order");
app.use("/order", orderRouter);

const bannerRouter = require("./router/banner");
app.use("/banner", bannerRouter);


// 定义错误中间件，捕获错误
app.use((err, req, res, next) => {
  res.cc(err);
})

// 开启服务器并监听80端口
app.listen(80, () => {
  console.log("server running at http://127.0.0.1:80");
});

